  var moduleCode;
  var topicId;
  var userId;
  var token;
  // for coundown timer
  var myTimer;
  var start, now, future;

  var questionHistoryArray;
  var answerArray;
  var choiceArray=["A", "B", "C", "D"];

  var myModuleInfo = null;
  var D, L, H, R;
  var questionId, questionSequence;
  var trainingStatus;

  var MAX_QUESTION = 25;
  var TRAINING_TIME_IN_MINUTE = 30;
  
  //function to get the query string parameters
  function getParameterByName(name) {
    name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
    var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
        results = regex.exec(location.search);
    return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
    }

  $(document).ready(function () {
    document.getElementById('question-wrapper').style.height = ($(window).height() - 100) + "px";
    document.getElementById('statistics-wrapper').style.height = ($(window).height() - 100) + "px";
    moduleCode = getParameterByName("moduleCode");
    topicId = getParameterByName("topicId");
    userId = getParameterByName("userId");
    token = getParameterByName("token");

    questionHistoryArray = new Array(MAX_QUESTION);
    answerArray = new Array(MAX_QUESTION);

    $('#nav-home-button').attr('href','index.html?userId=' + userId);
    $('#userName').html("User");

    InitTimer();

    InitialValues();
    GetQuestion();
  });

  var DrawChart = function() {
    // Donut Chart
    Morris.Donut({
        element: 'morris-chart',
        data: [{
            label: "Correct Answer",
            value: R
        }, {
            label: "Wrong Answer",
            value: (L - R)
        }],
        resize: true
    });
    $("#training-status").text(trainingStatus);

    var difference = Math.floor((now - start) / 1000);
    var seconds = fixIntegers(difference % 60);
    difference = Math.floor(difference / 60);

    var minutes = fixIntegers(difference % 60);
    difference = Math.floor(difference / 60);

    var hours = fixIntegers(difference % 24);
    difference = Math.floor(difference / 24);

    $("#time-complete").text(hours + ":" + minutes + ":" + seconds);
  };

  var GetQuestionDropDownList = function() {
//    div_str = " <div class=\"dropdown\"><button class=\"btn btn-default dropdown-toggle\" type=\"button\" data-toggle=\"dropdown\" aria-expanded=\"true\">Questions List<span class=\"caret\"></span></button><ul class=\"dropdown-menu\" role=\"menu\" aria-labelledby=\"dropdownMenu1\">";
    div_str = "<select class=\"form-control form-group\" id=\"review-question-select\" onchange=\"if (this.selectedIndex) ChangeQuestion();\">";
    for ( i = 1; i <= questionSequence; i++) {
//      div_Str += "<li role=\"presentation\"><a role=\"menuitem\" tabindex=\"-1\" href=\"#\">Question" + i + "</a></li>";
      div_str += "<option value=\"" + i + "\">Question " + i + "</option>";
    }
    div_str += "</select>";
    return div_str;
  }

  var InitTimer = function() {
    now = new Date();
    start = now;
    future = new Date(now.getTime() + TRAINING_TIME_IN_MINUTE*60000);

    myTimer = setInterval(function(){
      now = new Date();
      var difference = Math.floor((future - now) / 1000);

      if (difference == 0) {
        clearInterval(myTimer);
        EndTraining();
      } else {
        var seconds = fixIntegers(difference % 60);
        difference = Math.floor(difference / 60);

        var minutes = fixIntegers(difference % 60);
        difference = Math.floor(difference / 60);

        var hours = fixIntegers(difference % 24);
        difference = Math.floor(difference / 24);

        var days = difference;

        $("#seconds").text(seconds);
        $("#minutes").text(minutes);
        $("#hours").text(hours);
      }
    }, 1000);
  };


  var fixIntegers = function(integer) {
      if (integer < 0)
          integer = 0;
      if (integer < 10)
          return "0" + integer;
      return "" + integer;
  };

  var InitialValues = function() {
    D = 1;
    L = 0;
    H = 0;
    R = 0;
    questionSequence = 0;
  };

  var GetQuestion = function() {
    if (questionSequence == MAX_QUESTION) {
      bootbox.alert("You are not qualified for the topic, please try again!", function(){
        window.location = "index.html?userId=" + userId;
      });
    } else {
      url = "php/get_question.php?matric=" + userId + "&module=" + moduleCode + "&topic=" + topicId + "&difficulty=" + D;
      jQuery.getJSON(url, function (data) {
        questionSequence++;
        questionId = data.q_id;
        html_data = "<input id=\"choice_a\" type=\"radio\" name=\"answer\" value=\"1\">" + "<label for=\"choice_a\">" + data.choice_a + "</label>";
        html_data += "<br><input id=\"choice_b\" type=\"radio\" name=\"answer\" value=\"2\">" + "<label for=\"choice_b\">" + data.choice_b + "</label>";
        html_data += "<br><input id=\"choice_c\" type=\"radio\" name=\"answer\" value=\"3\">" + "<label for=\"choice_c\">" + data.choice_c + "</label>";
        html_data += "<br><input id=\"choice_d\" type=\"radio\" name=\"answer\" value=\"4\">" + "<label for=\"choice_d\">" + data.choice_d + "</label>";

        $('#question').html(questionSequence + ".  " + data.content);
        $('#choices').html(html_data);

        questionLevelData="";
        for (i = 0; i < data.diff_level; i++) {
          questionLevelData += "<span class=\"glyphicon glyphicon-star\"></span>";
        }
        for ( i = data.diff_level; i < 5; i++) {
          questionLevelData += "<span class=\"glyphicon glyphicon-star-empty\"></span>";
        }
        $('#question-level-div').empty();
        $('#question-level-div').html(questionLevelData);

        questionHistoryArray[questionSequence-1] = data;

        console.log(data.answer);
      });
    }
  };

  var SubmitAnswer = function() {
    answer = $('input[name="answer"]:checked').val();
    if(answer == undefined) {
      bootbox.alert("You must choose an answer to this question!", function(){});
    } else {
      answerArray[questionSequence-1] = answer;
      url = "php/update_values.php?matric=" + userId + "&module=" + moduleCode + "&topic=" + topicId + "&question=" + questionId + "&answer=" + answer + "&D=" + D + "&L=" + L + "&H=" + H + "&R=" + R + "&mode=training";
          
      jQuery.getJSON(url, function (data) {
        D = data.D;
        L = data.L;
        H = data.H;
        R = data.R;
        B = data.B;
        S = data.S;
        trainingStatus = data.status;

        console.log(data.lastResponseResult + ", " + trainingStatus + ", D = " + D + ", L =" + L + ", H = " + H + ", R = " + R + ", B = " + B + ", S = " + S);
              
        if (trainingStatus != "pass") {
          message = "";
          if (data.lastResponseResult == true) {
            message = "Your answer is <b>CORRECT</b>!";
          } else {
            message = "You answer in <b>INCORRECT</b>!"
          }
          bootbox.alert(message, function(){
            GetQuestion();
          });
        } else {
          EndTraining();
        }
      });
    }
  };

  var EndTraining = function() {
    bootbox.alert("Congratulation, you have completed this topic!", function(){
      $("#review-question-select-div").html(GetQuestionDropDownList);
      $("#question-wrapper").hide();
      $("#submit-wrapper").hide();
      $("#statistics-wrapper").show();
      DrawChart();
      ChangeQuestion();
    });
  };

  var ChangeQuestion = function() {
    questionNo = $("#review-question-select").val();
    $("#review-question-span").text(questionHistoryArray[questionNo-1].content);

    if (answerArray[questionNo-1] == 1)
      $("#review-choice-a-span").html("<input type=\"radio\" value=\"1\" disabled checked>" + questionHistoryArray[questionNo-1].choice_a);
    else
      $("#review-choice-a-span").html("<input type=\"radio\" value=\"1\" disabled>" + questionHistoryArray[questionNo-1].choice_a);
    
    if (answerArray[questionNo-1] == 2)
      $("#review-choice-b-span").html("<input type=\"radio\" value=\"2\" disabled checked>" + questionHistoryArray[questionNo-1].choice_b);
    else
      $("#review-choice-b-span").html("<input type=\"radio\" value=\"2\" disabled>" + questionHistoryArray[questionNo-1].choice_b);
    
    if (answerArray[questionNo-1] == 3)
      $("#review-choice-c-span").html("<input type=\"radio\" value=\"3\" disabled checked>" + questionHistoryArray[questionNo-1].choice_c);
    else
      $("#review-choice-c-span").html("<input type=\"radio\" value=\"3\" disabled>" + questionHistoryArray[questionNo-1].choice_c);
    
    if (answerArray[questionNo-1] == 4)
      $("#review-choice-d-span").html("<input type=\"radio\" value=\"4\" disabled checked>" + questionHistoryArray[questionNo-1].choice_d);
    else
      $("#review-choice-d-span").html("<input type=\"radio\" value=\"4\" disabled>" + questionHistoryArray[questionNo-1].choice_d);

    if (Number(questionHistoryArray[questionNo-1].answer) == answerArray[questionNo-1]) {
      $("#review-response-result-span").html("<font color=\"green\"><b>Your answer is CORRECT!</b></font>");
    } else {
      $("#review-response-result-span").html("<font color=\"red\"><b>Your answer is INCORRECT, correct answer is " + choiceArray[Number(questionHistoryArray[questionNo-1].answer)-1] + "!</b></font>");
    }
  };

  var GoHome = function() {
    window.location = "index.html?userId=" + userId;
  }

